package util

import (
	"fmt"
	"haodayizhi/global"
	"log"
	"os"
	"path"
	"time"
)

// enum 定义日志类型
const (
	LogTypeInfo  = "info"
	LogTypeError = "error"
)

// 创建日志文件
func createLogFile(logType string) (*os.File, error) {
	logDir := global.Config.Logging.Path
	if logType == "error" {
		logDir = path.Join(logDir, "error")
	} else {
		logDir = path.Join(logDir, "info")
	}

	if _, err := os.Stat(logDir); os.IsNotExist(err) {
		os.MkdirAll(logDir, 0755)
	}

	fileName := getLogFileName(logType)
	filePath := path.Join(logDir, fileName)
	file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return nil, err
	}
	return file, nil
}

// 通用日志记录函数
func LogMessage(logType, message string) {
	file, err := createLogFile(logType)
	if err != nil {
		fmt.Println("Error creating log file:", err)
		return
	}
	defer file.Close()

	logger := log.New(file, "", log.LstdFlags)
	logger.Println(message)
}

// 获取当前日期作为文件名
func getLogFileName(logType string) string {
	currentTime := time.Now()
	fileName := fmt.Sprintf("%s_%s.log", logType, currentTime.Format("20060102"))
	return fileName
}
